/*
 *  $Id: ObjectGameResolver.cs 1218 2010-11-28 14:03:06Z thenn.erannor $
 *  This file is a part of Ragima CCG.
 *  (C) 2008-2010 Ragima development group.
 *
 *  Licensed under the terms of the GNU GPL License version 2.
 *
 */

using Nereal.Extensions;
using Nereal.Serialization;

namespace Ragima.Serialization {
    public sealed class ObjectGameResolver : IKeyResolver<string, AbstractObject> {
        private const string CreatureKey = "creature";
        private const string LandKey = "land";

        public string ResolveKey(AbstractObject value) {
            if (value == null)
                return string.Empty;
            var playerId = Game.Current.GetPlayerId(value.Owner) ? "1" : "0";
            if (value is Player)
                return playerId;
            var parts = new string[3];
            parts[0] = playerId;
            if (value is Creature) {
                parts[1] = CreatureKey;
                parts[2] = ((Creature) value).Number.ToString();
            } else if (value is Land) {
                parts[1] = LandKey;
                parts[2] = ((Land) value).Number.ToString();
            } else
                return string.Empty;
            return string.Join("-", parts);
        }

        public AbstractObject ResolveValue(string key) {
            var parts = key.Split('-');
            if (parts.Length != 1 && parts.Length != 3)
                return null;
            var player = Game.Current.GetPlayerById(parts[0] == "1");
            if (parts.Length == 1)
                return player;
            int number;
            if (!int.TryParse(parts[2], out number))
                return null;
            if (parts[1] == CreatureKey)
                return number >= 0 && number < Constants.FieldSize ? player.GetCreature(number) : null;
            if (parts[1] == LandKey)
                return player.Lands.GetOrDefault(number);
            return null;
        }
    }
}
